package com.lpx.demo.demo.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lpx.demo.demo.config.listener.SessionListener;
import com.lpx.demo.demo.entity.BaseUserEntity;
import com.lpx.demo.demo.service.impl.base.BaseUserSerivceimpl;
import com.lpx.demo.demo.util.JsonResult;
import com.lpx.demo.demo.util.Md5Utils;
import com.lpx.demo.demo.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/user")

public class BaseUserController {
    @Autowired
    private BaseUserSerivceimpl userService;
    @Resource
    HttpServletRequest request;

    /**
     * @Description :用户注册
     * @Date 2021/1/30 11:32
     * @Author lpx
     */
    @PostMapping("/register")
    @ResponseBody
    public JsonResult registered(@RequestBody BaseUserEntity entity) {
        if (!userService.registered(entity)) {
            return JsonResult.error();
        }
        JsonResult result = JsonResult.success("注册成功");
        return result;
    }

    /**
     * @Description :用户登录
     * @Date 2021/1/30 11:32
     * @Author lpx
     */
    @PostMapping("/login")
    @ResponseBody
    public JsonResult login(@RequestBody JSONObject job) {
        String userName = job.getStr("userName");
        String password = job.getStr("password");
        JsonResult jsonResult = new JsonResult();
        jsonResult.put("code", "500");
        jsonResult.put("msg", "用户不存在");
        BaseUserEntity userEntity = userService.selectOne(new QueryWrapper<BaseUserEntity>().eq("user_name", userName));
        if (userEntity == null) {
            return jsonResult;
        }
        if (userEntity.getPassword().equals(Md5Utils.passwordToMd5(password, userEntity.getSalt()))) {
            HttpSession session = request.getSession();
            //如果用户已登录
            if(null !=SessionListener.sessionMap.get(userEntity.getId())){
                SessionUtils.forceLogoutUser(userEntity.getId());
            }
            SessionListener.sessionMap.put(userEntity.getId(),session);
            session.setAttribute("user",userEntity);
            jsonResult.put("code", "200");
            jsonResult.put("msg", "登录成功");
        }
        return jsonResult;
    }

    /**
    *
    * @Description :用户注销
    * @Date  2021/2/2 13:57
    * @Author lpx
    */
    @GetMapping(value = "/logout")
    public String logout(){
        request.getSession(false).invalidate();
        return "/home/login";
    }



}
